<script setup lang="ts">
import { tabBar } from '@/pages.json'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const isAgent = computed(() => userInfo.value?.customerType === 'agentCus')

// 响应式 tabbarList
const tabbarList = computed(() =>
  tabBar.list
    .filter(item => isAgent.value || item.text !== '代理商')
    .map(item => ({
      ...item,
      path: `/${item.pagePath}`,
      value: item.text === '订单' ? userStore.reportUnreadNumber : undefined,
    })),
)

const tabbarStore = reactive({
  curIdx: uni.getStorageSync('app-tabbar-index') || 0,
  setCurIdx(idx: number) {
    this.curIdx = idx
    uni.setStorageSync('app-tabbar-index', idx)
  },
})

function getCurrentPage() {
  const pages = getCurrentPages()
  return pages.length ? `/${pages[pages.length - 1].route}` : ''
}

onShow(async () => {
  const currentPage = getCurrentPage()
  await userStore.fetchUnreadReportNumber() // 获取最新未读数量
  // tabbarList.value.forEach(item => {
  //   if(item.text === '订单'){
  //     item.value = 12
  //   }
  // })
  const newIndex = tabbarList.value.findIndex(item => item.path === currentPage)
  if (newIndex !== -1) {
    tabbarStore.setCurIdx(newIndex)
  }
  else {
    const storedIdx = uni.getStorageSync('app-tabbar-index')
    tabbarStore.setCurIdx(storedIdx >= 0 && storedIdx < tabbarList.value.length ? storedIdx : 0)
  }
})

function isActive(idx: number) {
  return idx === tabbarStore.curIdx ? 'is-active' : 'is-inactive'
}

async function selectTabBar({value: index}: { value: number }) {
  if (index < 0 || index >= tabbarList.value.length) {
    return
  }
  const url = tabbarList.value[index].path
  tabbarStore.setCurIdx(index)
  uni.setStorageSync('app-tabbar-index', index)

  await userStore.fetchUnreadReportNumber() // 点击 tabbar 时也刷新

  try {
    uni.switchTab({url})
  } catch (err) {
    console.error('switchTab failed:', err)
  }
}

onLoad(() => {
  // H5 / App 原生 tabBar 隐藏
  // #ifdef APP-PLUS || H5
  uni.hideTabBar({
    fail(err) { console.log('hideTabBar fail: ', err) },
    success(res) { console.log('hideTabBar success: ', res) },
  })
  // #endif
})
</script>

<template>
  <wd-tabbar
    v-model="tabbarStore.curIdx"
    bordered
    safe-area-inset-bottom
    placeholder
    fixed
    @change="selectTabBar"
  >
    <block v-for="(item, idx) in tabbarList" :key="item.path">
      <wd-tabbar-item
        v-if="item.iconType === 'wot'"
        :title="item.text"
        :value="item.value"
        :icon="item.icon"
      />
      <wd-tabbar-item
        v-else-if="item.iconType === 'unocss' || item.iconType === 'iconfont'"
        :title="item.text"
        :value="item.value"
      >
        <template #icon>
          <view
            h-40rpx
            w-40rpx
            :class="[item.icon, isActive(idx)]"
            class="flex items-center justify-center !text-[19px]"
          />
        </template>
      </wd-tabbar-item>
      <wd-tabbar-item
        v-else-if="item.iconType === 'local'"
        :title="item.text"
        :value="item.value"
      >
        <template #icon>
          <image :src="item.icon" h-40rpx w-40rpx />
        </template>
      </wd-tabbar-item>
    </block>
  </wd-tabbar>
</template>
